package com.example.menuvirtualclient.repository;


import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;

import com.example.menuvirtualclient.core.*;
import com.example.menuvirtualclient.data.Repository;

public class MenuRepository extends Repository<Menu> {

	private static final String LOGTAG = "MenuRepository";
	
	public MenuRepository(Context context) {
		super(context);
	}	
	
	@Override
	public String getTableName() {
		return "Menus";
	}		
	
	public List<Menu> GetListBySeccion(int menutypeId) {
		SQLiteDatabase db = null;
		try{
			List<Menu> list = new ArrayList<Menu>();
			String[] filter = new String[1];
			filter[0] = Long.toString(menutypeId);
			if(!_session.IsOpen())
				_session.Open();
			
			db = _session.Connection();
			Cursor cursor = db.rawQuery("SELECT id, name, description, photo, status, menu_type_id FROM Menus WHERE menu_type_id = ?", filter);
			
			cursor.moveToFirst();
		    while (!cursor.isAfterLast()) {
		    	list.add(BuildNewEntity(cursor));
		    	cursor.moveToNext();
		    }
		    cursor.close();
		    db.close();
		    return list;
		}
		catch(SQLiteException ex){
			throw ex;
		}		
		finally{
			if(db != null)
				if(db.isOpen()) db.close();
		}
	}
		
	@Override
	public void Insert(Menu entity) {
		SQLiteDatabase db = null;
		try{
			ContentValues newRow = new ContentValues();
			newRow.put("id", entity.getId());			
			newRow.put("name", entity.getName());
			newRow.put("description", entity.getDescription());
			newRow.put("photo", entity.getPhoto());
			newRow.put("status", entity.getStatus());
			newRow.put("menu_type_id", entity.getMenu_type_id());	
			
			if(!_session.IsOpen())
				_session.Open();
			
			db = _session.Connection();
			db.insert(getTableName(), null, newRow);
			
			db.close();
		}
		catch(NullPointerException ex){
			Log.e(LOGTAG, ex.getMessage());
		}
		catch(SQLiteException ex){
			Log.e(LOGTAG, ex.getMessage());
		}
		catch(Exception ex){
			Log.e(LOGTAG, ex.getMessage());		
		}
		finally{
			if(db != null)
				if(db.isOpen()) db.close();
			_session.Close();
		}
	}	
		
	@Override
	public Menu BuildNewEntity(Cursor cursor) {
		Menu menu = new Menu();
		menu.setId(cursor.getInt(0));
		menu.setName(cursor.getString(1));
		menu.setDescription(cursor.getString(2));
		menu.setPhoto(cursor.getString(3));
		menu.setStatus(cursor.getInt(4));
		menu.setMenu_type_id(cursor.getInt(5));
		
		return menu;
	}
	
}
